package com.itic.mall.mobile.pay;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.type.PayType;
import com.itic.appbase.framework.utils.CompanyPayVo;
import com.itic.appbase.framework.utils.PayVo;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.WeixinPayUtil;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;


@Controller
@RequestMapping(value="/mobile/wxpay")
public class WxPayInterface
     extends BaseMobileInterface {
	
	/**
	 * 微信支付成功回调
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/success")   
	@ResponseBody 
	public void notify(HttpServletRequest request,HttpServletResponse response){  
		 try{  
             //处理自己的业务逻辑  
			 PaySuccessVo paySuccessVo = WeixinPayUtil.success(request, response);//获取订单号码	
			 String orderNum = paySuccessVo.getOrderNo();
			 String payNo = paySuccessVo.getPayNo();
			 String payTime = paySuccessVo.getPayTime();
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
			 Date date = sdf.parse(payTime); 
			 String dealResult = FAIL;
			 //处理用户订单状态为已支付状态
			 //dealResult = dealOrderByorderNo(orderNum,payNo,date,"002");//支付类型（001：支付宝，002：微信，003：余额）		 
			 dealResult = this.ordersDetailService.aliPaySuccess(orderNum, payNo, PayType.wx, date);
			 if(SUCCESS.equals(dealResult)){
				 System.out.println(orderNum);
	             response.getWriter().write(WeixinPayUtil.setXml(SUCCESS, "OK"));    //告诉微信已经收到通知了 
			 }
			 
          }catch(Exception e){  
        	  logException("WeixinPay", "success", e.toString(),"微信APP支付回调",e);
          } 
	}  
	    
	/**
	 * 微信支付
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param orderNum
	 * @return
	 */
	@RequestMapping(value="/pay")
	@ResponseBody
	public Map<String,Object> pay( HttpServletRequest request,HttpServletResponse response, String token,String appId,String orderNo ){
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(orderNo) ){
				UsersMall user = getUsersByTokenAndAppId(token, appId);
				if( null != user ){
					String userId = user.getId();
					OrdersDetail ordersDetail = getOrderByOrderNo(userId,orderNo,"1");
			    	String orderDesc = getDescByOrderNo(orderNo);
					if(ordersDetail != null){
						if( orderDesc.length()>20 ){
							orderDesc = orderDesc.substring(0, 20)+"...";
						}
						orderDesc = ordersDetail.getUserNickName() +"在"+ordersDetail.getCreateTime()+"购买商品"+orderDesc;
						//验证订单
						//Order order = verifyOrder(user.getId(),orderNum);
						PayVo payVo = new PayVo();
						payVo.setDesc(orderDesc);
						payVo.setOrderNum(orderNo);
						payVo.setTotalMoney(ordersDetail.getActualPay().toString());
				        Map<String, Object> jsonPay = WeixinPayUtil.pay(request, getWxpayConfig(),payVo);
				        resultMap.put(DATA, jsonPay);			        
						errorCode = SUCCESS_ERROR_CODE;
				    	errorMsg = SUCCESS_ERROR_MSG;
					}else{
						errorCode = ORDER_ERROR_CODE;
						errorMsg = ORDER_ERROR_MSG;
					}
				}else{
					errorCode = LOGIN_ERROR_CODE;
			    	errorMsg = LOGIN_ERROR_MSG;
				}
			}
		}catch (Exception e) {
			 errorCode = SERVER_ERROR_CODE;
		     errorMsg = SERVER_ERROR_MSG;
			 logException("WeixinPay", "pay", e.toString(),"微信APP支付",e);
		}
    	resultMap.put(CODE, errorCode);
    	resultMap.put(MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	@RequestMapping(value = "/companysuccess")   
	@ResponseBody 
	public void companynotify(HttpServletRequest request,HttpServletResponse response){  
		 try{  
             //处理自己的业务逻辑  
			 PaySuccessVo paySuccessVo = WeixinPayUtil.success(request, response);//获取订单号码	
			 String orderNum = paySuccessVo.getOrderNo();
			 String payNo = paySuccessVo.getPayNo();
			 String payTime = paySuccessVo.getPayTime();
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
			 Date date = sdf.parse(payTime); 
			 String dealResult = FAIL;
			 //处理用户订单状态为已支付状态
			 //dealResult = dealOrderByorderNo(orderNum,payNo,date,"002");//支付类型（001：支付宝，002：微信，003：余额）		 
			 if(SUCCESS.equals(dealResult)){
				 System.out.println(orderNum);
	             response.getWriter().write(WeixinPayUtil.setXml(SUCCESS, "OK"));    //告诉微信已经收到通知了 
			 }
			 
          }catch(Exception e){  
        	  logException("WeixinPay", "success", e.toString(),"微信APP支付回调",e);
          } 
	}
	/**
	 * 企业支付
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param orderNum
	 * @param openid
	 * @param amount
	 * @return
	 */
	@RequestMapping(value = "/companypay")
	@ResponseBody
	public Map<String, Object> companypay(HttpServletRequest request, HttpServletResponse response,
			String orderNoSkuIds, String orderNum, String openid, int amount) {
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// orderNoSkuIds格式，orderNo:skuId:aliId:realName,orderNo:skuId:aliId:realName,orderNo:skuId:aliId:realName
			// 根据订单号获取订单描述
			
			if (StringHelper.isNotBlank(orderNum)) {
				CompanyPayVo companyPayVo = new CompanyPayVo();
				companyPayVo.setAmount(amount);
				companyPayVo.setPartner_trade_no(orderNum);
				companyPayVo.setOpenid(openid);
				Map<String, Object> jsonPay = WeixinPayUtil.companypay(request, getWxCompanyPay(), companyPayVo);
				resultMap.put(DATA, jsonPay);
				errorCode = SUCCESS_ERROR_CODE;
		    	errorMsg = SUCCESS_ERROR_MSG;
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("WxPayInterface", "companypay", e.toString(), "微信企业支付", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
    	return resultMap;
		}
	/**
	 * 微信退款
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param orderNum
	 * @return
	 */
	@RequestMapping(value="/back")
	@ResponseBody
	public Map<String,Object> back( HttpServletRequest request,HttpServletResponse response, String token,String appId,String orderNum ){
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(orderNum) ){
			UsersMall user = getUsersByTokenAndAppId(token, appId);
			if( null != user ){
				//验证订单
				//Order order = verifyOrder(user.getId(),orderNum);
				PayVo payVo = new PayVo();
				payVo.setDesc("测试");
				payVo.setOrderNum(orderNum);
				payVo.setTotalMoney("0");
		        WeixinPayUtil.back(request, getWxpayConfig(),payVo);
		        
				errorCode = SUCCESS_ERROR_CODE;
		    	errorMsg = SUCCESS_ERROR_MSG;
			}else{
				errorCode = LOGIN_ERROR_CODE;
		    	errorMsg = LOGIN_ERROR_MSG;
			}
		}
    	resultMap.put(CODE, errorCode);
    	resultMap.put(MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	
}